<?php

namespace app\common\model\merchant;


use app\common\model\BaseModel;
use think\Exception;

/**
 * 商户订单明细表
 * Class OrderDetail
 * @package app\common\model
 */
class OrderDetailModel extends BaseModel
{
    //
    protected $name = 'order_detail';

    // 设置字段信息
    protected $schema = [
        'id' => 'int',        // 序号
        'order_no' => 'string',        // 订单号
        'mer_id' => 'string',        //
        'shop_id' => 'int',        // 店铺ID
        'product_code' => 'string',        // 商品code
        'num' => 'int',        // 商品数量
    ];


    /**
     * 添加订单明细
     * @param        $order_no |订单号
     * @param array  $data |添加数据
     * @param int    $shop_id | 店铺
     * @param string $mer_id
     * @return array
     * @throws Exception
     */
    public function orderAdd($order_no, array $data, int $shop_id, string $mer_id): array
    {

        $insertData = [];
        foreach ($data as $v) {
            $insertData[] = [
                'order_no' => $order_no,
                'mer_id' => $mer_id,
                'shop_id' => $shop_id,
                'product_code' => $v['product_code'],
                'num' => $v['num'],
            ];
        }
        $datas = $this->db()->insertAll($insertData);
        if (!$datas) {
            throw  new Exception('创建失败', API_ERROR);
        }
        return $data;

    }

    /**
     * 根据订单号获取订单的商品列表
     * @param string $orderNo
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(string $orderNo)
    {
        return $this->db()->alias('a')->join('product b', 'a.product_code=b.code', 'left')
            ->where('order_no', $orderNo)
            ->where('a.mer_id=b.mer_id')
            ->field("a.product_code||'|'||b.title as product,a.num")
            ->select();
    }
}
